%[rings main] = findRings(main)
%   This function finds all the elements per ring by running the function
%   'search' on every ringmarker from 1 to the maximum ringmarker in main.
%   It also adds a field 'ring' to main in which the rings the element
%   belongs to are added.
%   It therefore returns a struct 'rings' and a struct 'main' from a struct
%   'main'.

function [rings main] = findRings(main)
%% Initialise

%This function can only run when all the field 'ringmarker' in 'main'
%contains only numeric values and no empty spots. The following checks if
%there are any empty spots in the 'ringmarker' field and replaces them by
%zeros if necessary.
for j = 1:length(main)
    if isempty(main(j).ringmarker)
        main(j).ringmarker = 0;
    end
end

%This function requires the field 'ring' to exist and therefore checks it's
%existance and adds it if necessary.
if ~myIsField(main,'ring')
    main(1).ring = [];
end

%% Main
%For all ringmarkers in the field 'ringmarker' (from 1 to the maximum in
%this particular field should be all ringmarkers),
for j = 1:max([main.ringmarker])
    %'posFound' Starts at the length of 'main'.
    posFound = length(main);
    %for all elements in 'main',
    for k = 1:length(main)
        %if they have the ringmarker that is searched has been found at
        %elements 'k',
        if sum(main(k).ringmarker == j);
            %and the position 'k' is closer to the beginning of main than
            %the previous found position, change 'posFound' to the value of
            %'k' and break.
            if k < posFound
                posFound = k;
                break
            end
        end
    end
    %The first position of ringmarker 'j' has been found at 'posFound' and
    %is stored in the array 'position'.
    position(j) = posFound;
end

%For all ringmarkers,
for j = 1:max([main.ringmarker])
    %search the elements of this ring and return them by using the function
    %'search' and add these elements to the struct 'rings'.
    rings(j).elements = search(main,position(j),j,1);
    %For the length of this ring, add the ringmarker to the elements in the
    %ring.
    for k = 1:length(rings(j).elements)
        main(rings(j).elements(k)).ring = ...
            [main(rings(j).elements(k)).ring j];
    end
end

%If no the struct 'rings' has not been created because there were no rings,
%return an empty struct.
if ~exist('rings','var')
    rings = [];
end

%% End
end  